package logic;

import java.awt.Color;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateXlsx {

	/**
	 * 用于缓存单元格格式.
	 */
	private static final Map<Integer, XSSFCellStyle> CACHE = new HashMap<>(64000);

	/**
	 * 生成成品Excel.
	 * @param list
	 * @param path
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	static void create(List<int[]> list, String path) throws Exception {
		// 先保存一个空Excel文件，在磁盘占位
		XSSFWorkbook excel = new XSSFWorkbook();
		excel.createSheet("myPic");
		path = saveExcel(path, excel);

		int size = list.size();
		int length = list.get(0).length;

		// 读取占位的文件，设置列宽
		System.out.println("Start setting the style of cells…");
		excel = new XSSFWorkbook(new FileInputStream(path));
		XSSFSheet sht = excel.getSheetAt(0);
		for (int j = 0; j < length; j++)
			sht.setColumnWidth(j, (short) 500);

		// 缓存所需的所有单元格格式
		XSSFCellStyle xstyle = excel.createCellStyle();
		for (int i = 0; i < size; i++)
			for (int rgb : list.get(i)) {
				Integer key = Integer.valueOf(rgb);
				if (CACHE.get(key) == null) {
					XSSFCellStyle style = (XSSFCellStyle) xstyle.clone();
					style.setFillForegroundColor(new XSSFColor(new Color(rgb)));
					style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
					CACHE.put(key, style);
				}
			}

		// 开始按行填充颜色
		System.out.println("Start filling cells…");
		for (int i = 0; i < size; i++) {
			int[] rgbs = list.get(i);
			Row row = sht.createRow(i);
			// 设置行高，使之与列宽相等（即：设置单元格为正方形）
			row.setHeight((short) 250);
			for (int j = 0; j < length; j++)
				row.createCell(j).setCellStyle(CACHE.get(rgbs[j]));
		}

		saveExcel(path, excel);
		System.out.println("Done");// 提示完成
	}

	private static String saveExcel(final String path, XSSFWorkbook excel) throws Exception {
		try {
			FileOutputStream out = new FileOutputStream(path);
			excel.write(out);
			excel.close();
			out.close();
		} catch (Exception e) {
			throw new Exception("Cannot write an excel file to disk.", e);
		}
		return path;
	}

}